package com.xinhe.web.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.weixin.service.WeixinUtilBean;
import org.apache.commons.io.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.FileAttribute;
import java.util.Map;
import java.util.UUID;

@Component
public class WeixinUtil {
    @Autowired
    private WeixinUtilBean weixinUtilBean;

    @Retryable(value = {BusinessException.class}, maxAttempts = 1, backoff = @Backoff(delay = 1L, multiplier = 0.0D))
    public Result<File> miniProgramQrcodeUnLimit(Map<String, Object> params, Long configId) {
        Result<File> result = new Result();
        WeixinUtilBean.TicketToken ticketToken = this.weixinUtilBean.getTicketToken(configId);
        try {
            String mimeType = ContentType.APPLICATION_JSON.getMimeType();
            HttpPost post = new HttpPost(String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", new Object[] { ticketToken.getAccessToken() }));
            post.setHeader("Content-Type", mimeType);
            post.setEntity((HttpEntity)new StringEntity(JSONObject.toJSONString(params)));
            CloseableHttpResponse response = HttpClientBuilder.create().build().execute((HttpUriRequest)post);
            HttpEntity entity = response.getEntity();
            Header[] contentTypeHeader = response.getHeaders("Content-Type");
            if (mimeType.equals(ContentType.parse(contentTypeHeader[0].getValue()).getMimeType())) {
                throw new BusinessException(4100,EntityUtils.toString(entity));
            }
            File resultFile = File.createTempFile(UUID.randomUUID().toString(), ".jpeg", Files.createTempDirectory("qrcode-temp", (FileAttribute<?>[])new FileAttribute[0]).toFile());
            resultFile.deleteOnExit();
            FileUtils.copyInputStreamToFile(entity.getContent(), resultFile);
            result.setData(resultFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Recover
    private Result<File> miniProgramQrcodeUnLimitRecover(BusinessException e, Map<String, Object> params, Long configId) {
        Result<File> result = new Result();
        JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
        int errcode = jsonObject.getInteger("errcode");
        if (errcode == 40001 || errcode == 42001) {
            this.weixinUtilBean.refreshWeixinFlag(configId);
            return miniProgramQrcodeUnLimit(params, configId);
        }
        return Result.failed(42001,jsonObject.toString());
    }
}